package server

import (
	"errors"
	"math/rand"
	"onerk4/zk2/common/dao/dao_mysql"
	"onerk4/zk2/common/dao/dao_redis"
	"onerk4/zk2/common/pkg"
	user "onerk4/zk2/common/proto"
	"strconv"
)

func UserLogin(req *user.UserLoginRequest) (*user.UserLoginResponse, error) {
	getSms, err := dao_redis.GetSms(req.Mobile, "login")
	if err != nil {
		return nil, err
	}
	if getSms != req.Sms {
		return nil, errors.New("验证码错误")
	}

	userInfo, err := dao_mysql.QueryUserByMobile(req.Mobile)
	if err != nil {
		return nil, err
	}

	if userInfo.ID == 0 {
		return nil, errors.New("没有该账号")
	}

	if userInfo.Passwd != req.Password {
		return nil, errors.New("密码错误")
	}

	claims := pkg.CustomClaims{ID: uint(userInfo.ID)}
	token, err := pkg.NewJWT("2209a").CreateToken(claims)
	if err != nil {
		return nil, errors.New("token生成失败")
	}

	return &user.UserLoginResponse{Success: token}, nil
}

func SendSms(req *user.SendSmsRequest) (*user.SendSmsResponse, error) {

	code := rand.Intn(9000) + 1000

	//sms, _ := pkg.SendSms(req.Mobile, strconv.Itoa(code))
	//if *sms.Body.Code != "OK" {
	//	return nil, errors.New(*sms.Body.Message)
	//}

	err := dao_redis.SetSms(req.Mobile, req.Source, strconv.Itoa(code))
	if err != nil {
		return nil, errors.New("存入redis失败")
	}

	getSms, err := dao_redis.GetSms(req.Mobile, req.Source)
	if err != nil {
		return nil, err
	}

	return &user.SendSmsResponse{Sms: getSms}, nil
}

func SearchEnterpriseData(req *user.SearchEnterpriseDataRequest) (*user.SearchEnterpriseDataResponse, error) {
	if req.StoreName == "" {
		data, err := dao_mysql.QuerySearchEnterpriseData(req.Uid)
		if err != nil {
			return nil, err
		}

		err = dao_redis.SetSearchEnterpriseData(data)
		if err != nil {
			return nil, err
		}

		var items []*user.SearchEnterpriseDataItem

		for _, item := range data {
			items = append(items, &user.SearchEnterpriseDataItem{
				Id:        item.Id,
				MerId:     item.MerId,
				Image:     item.Image,
				StoreName: item.StoreName,
				StoreInfo: item.StoreInfo,
				Price:     float32(item.Price),
				Sales:     item.Sales,
				Stock:     item.Stock,
				Collect:   item.Collect,
				Browse:    item.Browse,
			})
		}
		return &user.SearchEnterpriseDataResponse{List: items}, nil
	} else {
		data, err := dao_mysql.QuerySearchEnterpriseDataLike(req.Uid, req.StoreName)
		if err != nil {
			return nil, err
		}

		var items []*user.SearchEnterpriseDataItem

		for _, item := range data {
			items = append(items, &user.SearchEnterpriseDataItem{
				Id:        item.Id,
				MerId:     item.MerId,
				Image:     item.Image,
				StoreName: item.StoreName,
				StoreInfo: item.StoreInfo,
				Price:     float32(item.Price),
				Sales:     item.Sales,
				Stock:     item.Stock,
				Collect:   item.Collect,
				Browse:    item.Browse,
			})
		}
		return &user.SearchEnterpriseDataResponse{List: items}, nil
	}
}
